package com.gljx.web.controller;

/**
 * Created by Administrator on 2017/11/7 0007.
 */

import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.RecordoutMapper;
import com.gljx.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author lcx
 * @Date 2017/11/7 0007 上午 8:56
 * 档案管理
 */
@Controller
@RequestMapping("/")
public class RecordOutController {

    @Autowired
    RecordoutService recordoutService;

    @Autowired
    RecordoutentryService recordoutentryService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    CustomLogService customLogService;
    @Autowired
    RecordoutMapper recordoutMapper;
    @Autowired
    private StudentService studentService;

    /**
     * @Author lcx
     * @Date 2017/11/7 0007 上午 9:10
     * 查询档案列表
     */
    @RequestMapping("/queryRecordout/look.action")
    public String queryRecordout(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "alertType", defaultValue = "") String alertType) {

        PageBean<Recordout> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            if (fnumber != null && !fnumber.equals("")) {
                //页面搜索模糊查询
                //获取分页
                pb = getPageBean(request, user.getFcompanyid(), fnumber);
            } else {
                //获取分页
                pb = getPageBean(request, user.getFcompanyid(), null);
            }
            //获取当前分页的值
            List<Recordout> recordoutList = pb.getBeanList();
            //把获取到的数据传回页面

            for (Recordout recordout : recordoutList) {
                //查询学员信息
                recordout.setRecordoutentryList(recordoutentryService.selectRecordoutentryByFid(recordout.getFid()));
            }

            request.setAttribute("recordoutList", recordoutList);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("pb", pb);
            request.setAttribute("alertType", alertType);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/recordinAdmin/insRecordin/RecordoutList";
    }


    @SuppressWarnings("unchecked")
    /**
     * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
     * @return 返回PageBean实体类
     * @throws Exception
     */
    public PageBean<Recordout> getPageBean(HttpServletRequest request, String companyId, String fnumber) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (fnumber == null) {
            psql.append("SELECT R.fid, R.FNUMBER, TO_CHAR(R.FBIZDATE, 'YYYY-MM-DD') FBIZDATE, R.FDESCRIPTION, E.NAME AS checkName, U.NAME AS createName, CFBILLSTATE" +
                    " FROM CT_DS_RECORDOUT R LEFT JOIN T_E_USER E ON R.FAUDITORID = E.FID LEFT JOIN T_E_USER U ON R.FCREATORID = U.FID");
            psql.append(" where R.FCONTROLUNITID= '" + companyId + "' ORDER BY fcreatetime DESC");
        } else {
            psql.append("SELECT R.fid, R.FNUMBER, TO_CHAR(R.FBIZDATE, 'YYYY-MM-DD') FBIZDATE, R.FDESCRIPTION, E.NAME AS checkName, U.NAME AS createName, CFBILLSTATE" +
                    " FROM CT_DS_RECORDOUT R LEFT JOIN T_E_USER E ON R.FAUDITORID = E.FID LEFT JOIN T_E_USER U ON R.FCREATORID = U.FID");
            psql.append(" where R.FNUMBER like '%" + fnumber + "%' AND R.FCONTROLUNITID= '" + companyId + "' ORDER BY fcreatetime DESC");
        }

        int psize = 5; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = recordoutService.selectPage(pindex, psql.toString(), psize);
        PageBean<Recordout> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Recordout>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }


    /**
     * 取记录总数 dmz 20160921
     *
     * @param psql SQL语句
     * @return Map
     * @throws Exception
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = recordoutService.selectPageCount(psql);
        return paramMap;
    }

    /**
     * @Author lcx
     * @Date 2017/11/9 0009 下午 2:12
     * 跳转到添加页面
     */
    @RequestMapping(value = "/go_add_Recordout")
    public String goAddRecordout(HttpServletRequest request, String alertType) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        /*String number = customLogService.selectFunmber("CT_DS_RECORDOUT",user.getFcompanyid());*/
        String fnumber = GetFnumber.fnumbers("DACK");
        Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
        ca.setTime(new Date()); // 设置时间为当前时间
        ca.add(Calendar.MONTH, -3);// 月份减1
        Date resultDate = ca.getTime(); // 结果
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = sdf.format(resultDate);
        String endTime = sdf.format(new Date());

        Map map = getPageAsRecordin(request, "", "", "0", beginTime, endTime);

        request.setAttribute("beginTime", beginTime);
        request.setAttribute("endTime", endTime);
        request.setAttribute("createname", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("fbizdate", TimeFormat.getNowTime());
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb", map.get("pb"));
        request.setAttribute("students", map.get("sList"));
        request.setAttribute("alertType", alertType);

        return "/backHome/recordinAdmin/insRecordin/RecordoutAdd";
    }

    @RequestMapping(value = "go_update_recordout")
    public String goUpdateRecordout(HttpServletRequest request, String fid, String xqid) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //根据fid查询
        Recordout recordout = recordoutService.selectRecordoutByFid(fid);
        List<Recordoutentry> recordoutentryList = recordoutentryService.selectRecordoutentryByFid(fid);

        Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
        ca.setTime(new Date()); // 设置时间为当前时间
        ca.add(Calendar.MONTH, -3);// 月份减1
        Date resultDate = ca.getTime(); // 结果
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = sdf.format(resultDate);
        String endTime = sdf.format(new Date());

        Map map = getPageAsRecordin(request, "", "", "0", beginTime, endTime);

        request.setAttribute("beginTime", beginTime);
        request.setAttribute("endTime", endTime);


        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("recordout", recordout);
        request.setAttribute("recordoutentryList", recordoutentryList);
        request.setAttribute("pb", map.get("pb"));
        request.setAttribute("students", map.get("sList"));

        return "/backHome/recordinAdmin/insRecordin/updateRecordout";
    }

    /**
     * @Author lcx
     * @Date 2017/11/8 0008 下午 3:47
     * 更新数据
     */
    @RequestMapping(value = "/update_recordout")
    public String updateRecordout(HttpServletRequest request, Recordout recordout) {

        Axamine axamine = new Axamine();

        String[] rfid = request.getParameterValues("rfid");
        String[] rfseq = request.getParameterValues("rfseq");
        String[] rstuname = request.getParameterValues("rstuname");
        String[] rcfstudentno = request.getParameterValues("rcfstudentno");
        String[] rcfidcardno = request.getParameterValues("rcfidcardno");
        String[] rcfcartype = request.getParameterValues("rcfcartype");
        String[] rcfcfwz = request.getParameterValues("rcfcfwz");
        String[] rcfremark = request.getParameterValues("rcfremark");
        Recordout recordouttem = recordoutMapper.selectByPrimaryKey(recordout.getFid());

        recordout.setFcreatorid(recordouttem.getFcreatorid());
        recordout.setFcreatetime(recordouttem.getFcreatetime());
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        recordout.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        recordout.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String updateTime = TimeFormat.timeFormat(new Date());
        //修改时间
        recordout.setFlastupdatetime(updateTime);
        //修改人id
        recordout.setFlastupdateuserid(user.getFid());
        //创建人id
        //删除之前的记录
        recordoutService.deleteRecordouAndRecordoutentry(recordout.getFid());


        String uuid = GetFid.UUIDIntoFid();
        recordout.setFid(uuid);

        //为了消除提交页面点击确定丢失审核人的 问题
        if ("2".equals(recordout.getFfivouchered() + "")) {
            recordout.setFauditorid(recordouttem.getFauditorid());
            recordout.setCfbillstate(Long.valueOf("3"));
        }

        for (int i = 0; i < rfid.length; i++) {
            Recordoutentry recordoutentry = new Recordoutentry();
            recordoutentry.setFid(GetFid.UUIDIntoFid());
            recordoutentry.setFparentid(uuid);
            recordoutentry.setFseq(Long.valueOf(rfseq[i]));
            recordoutentry.setCfstudentid(rstuname[i]);
            recordoutentry.setCfstudentno(rcfstudentno[i]);
            recordoutentry.setCfidcardno(rcfidcardno[i]);
            recordoutentry.setCfcartype(rcfcartype[i]);
            recordoutentry.setCfcfwz(rcfcfwz[i]);
            recordoutentry.setCfremark(rcfremark[i]);

            recordoutentryService.addRecordoutentry(recordoutentry);
        }

        //更新数据操作
        recordoutService.addRecordout(recordout);
        //添加日志
        customLogService.addLog("档案管理", TimeFormat.timeFormat(new Date()) + "对档案出库进行更新", null, user.getFid());


        return "redirect:/DrivingSys/queryRecordout/look.action?state=first&alertType=qd";
    }

    /**
     * @Author lcx
     * @Date 2017/11/11 0011 上午 8:44
     */
    @RequestMapping(value = "/add_recordout")
    public String addRecordout(HttpServletRequest request, Recordout recordout) {

        String[] rfid = request.getParameterValues("rfid");
        String[] rfseq = request.getParameterValues("rfseq");
        String[] rstuname = request.getParameterValues("rstuname");
        String[] rcfstudentno = request.getParameterValues("rcfstudentno");
        String[] rcfidcardno = request.getParameterValues("rcfidcardno");
        String[] rcfcartype = request.getParameterValues("rcfcartype");
        String[] rcfcfwz = request.getParameterValues("rcfcfwz");
        String[] rcfremark = request.getParameterValues("rcfremark");
        /*获取uuid*/
        String uuid = GetFid.UUIDIntoFid();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        recordout.setFid(uuid);
        //公司id
        recordout.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        recordout.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        recordout.setFcreatetime(createTime);
        //修改人id
        recordout.setFcreatorid(user.getFid());

        for (int i = 0; i < rfid.length; i++) {
            Recordoutentry recordoutentry = new Recordoutentry();
            recordoutentry.setFid(GetFid.UUIDIntoFid());
            recordoutentry.setFparentid(uuid);
            recordoutentry.setFseq(Long.valueOf(rfseq[i]));

            recordoutentry.setCfstudentid(rstuname[i]);
            recordoutentry.setCfstudentno(rcfstudentno[i]);
            recordoutentry.setCfidcardno(rcfidcardno[i]);
            recordoutentry.setCfcartype(rcfcartype[i]);
            recordoutentry.setCfcfwz(rcfcfwz[i]);
            recordoutentry.setCfremark(rcfremark[i]);

            recordoutentryService.addRecordoutentry(recordoutentry);
        }
        //更新数据操作
        recordoutService.addRecordout(recordout);

        //添加日志
        customLogService.addLog("档案管理", TimeFormat.timeFormat(new Date()) + "对档案出库进行新增", null, user.getFid());


        return "redirect:/DrivingSys/go_add_Recordout?alertType=bc";
    }


    /**
     * @Author lcx
     * @Date 2017/11/2 0002 下午 4:28
     * 对财务基础资料删除
     */
    @RequestMapping(value = "delete_recordout")
    public String deleteRecordout(HttpServletRequest request, String[] deleteId, String[] fnumber) throws Exception {

        User user = (User) request.getSession().getAttribute("user");
        /*删除 子类也删除*/
        recordoutService.deleteByRecordoutKey(deleteId, fnumber);

        //添加日志
        customLogService.addLog("档案管理", TimeFormat.timeFormat(new Date()) + "对档案出库进行删除", null, user.getFid());

        return "redirect:/DrivingSys/queryRecordout/look.action";
    }

    /**
     * @Author lcx
     * @Date 2017/11/16 0016 上午 8:47
     * 档案管理查询学生档案入库的信息
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getPageasrecordin")
    public Map getPageAsRecordin(HttpServletRequest request, @RequestParam(defaultValue = "") String name, @RequestParam(defaultValue = "") String cflxdh, @RequestParam(defaultValue = "0") String pindex, String beginTime, String endTime) throws Exception {
        String psql = "SELECT S.FID,S.FNAME_L2,S.FNUMBER,S.CFSJHM,S.cflxdh,s.CFADDRESS,s.CFLINKADDRESS," +
                "  TO_CHAR(S.CFBIRTHDAY, 'YYYY-MM-DD') CFBIRTHDAYS,s.CFIDCARDNO,D.CFJYZBH CFJSYBH,D.CFCFWZ," +
                "  s.CFAMOUNT,s.CFRECEIVED,s.CFARREARAGE,s.CFFAVORABLE,A.FNAME_L2 FCONTROLUNITID,r.CFBILLSTATE CFBILLSTATE" +
                "" +
                " FROM CT_DS_RECORDIN R" +
                "  LEFT JOIN CT_DS_RECORDINENTRY D ON R.FID = D.FPARENTID" +
                "  LEFT JOIN CT_DS_STUDENT S ON S.FID = D.CFSTUDENTID" +
                "  LEFT JOIN CT_DS_ADMIN A ON S.FCONTROLUNITID = A.FID";
        psql += " where S.FNAME_L2 like '%" + name + "%' ";
        if (!"".equals(cflxdh)) {
            psql += "and S.cflxdh like '%" + cflxdh + "%' ";
        }
        if (!"".equals(beginTime) && !"".equals(endTime)) {
            psql += "AND (s.CFRXSJ BETWEEN to_date('" + beginTime + "','YYYY/MM/DD') AND to_date('" + endTime + "','YYYY/MM/DD'))";
        }
        int psize = 50; //每页显示数
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = studentService.selectPage(Integer.valueOf(pindex), psql, psize);
        PageBean<Student> pb = new PageBean<>();
        pb.setPc(Integer.valueOf(pindex)); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        Map stu = new HashMap();
        stu.put("sList", (List<Student>) paramMap.get("v_cur"));

        stu.put("pb", (pb.getTr() / pb.getPs()));

        return stu; //每页数据集;

    }

    /**
     * @Author lcx
     * @Date 2018/2/5 0005 下午 4:27
     */
    @RequestMapping(value = "/queryRecordoutExamine")
    @ResponseBody
    public ServerResponse examine(HttpServletRequest request, @RequestParam(defaultValue = "", value = "fid") String fid,
                                  @RequestParam(defaultValue = "", value = "state") String state,
                                  @RequestParam(defaultValue = "", value = "agreed") String agreed,
                                  @RequestParam(defaultValue = "", value = "auditcomment") String auditcomment,
                                  @RequestParam(defaultValue = "", value = "fnumber") String fnumber) {
        Recordout recordout = new Recordout();

        recordout.setFid(fid);
        recordout.setFnumber(fnumber);

        return recordoutService.examine(recordout, state, agreed, auditcomment);
    }

    /**
     * @Author lcx
     * @Date 2018/2/27 0027 上午 11:49
     * 提交
     */
    @RequestMapping(value = "/queryRecordoutSubmit")
    @ResponseBody
    public ServerResponse submit(HttpServletRequest request,
                                 @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                 @RequestParam(defaultValue = "", value = "fid") String fid) {
        Axamine axamine = new Axamine();
        Recordout recordout = new Recordout();

        recordout.setFid(fid);
        /*recordout.setFauditorid(((User) request.getSession().getAttribute("user")).getFid());*/
        recordout.setCfbillstate(Long.valueOf("4"));
        recordoutMapper.updateByPrimaryKeySelective(recordout);
        return axamine.submissionProcess(String.valueOf(fnumber));
    }

    @RequestMapping("/queryRecordoutXls")
    public String queryRecordinXls(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                   @RequestParam(defaultValue = "", value = "name") String name,
                                   @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                   @RequestParam(defaultValue = "", value = "endTime") String endTime) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String head[] = {"单据编号", "业务日期", "参考消息", "审核人", "制单人", "单据状态", "学员", "学员编号", "身份证号码", "车型",
                "结业时间", "备注"
        };
        //长度
        Integer length[] = {8500, 5000, 6000, 3000, 3000, 3000, 3000, 6000, 6000, 3000,
                5000, 5000};

        List<Recordoutentry> recordoutentryList = recordoutService.selectRecordoutXls(fnumber, name, beginTime, endTime, user.getFcompanyid());


        for (Recordoutentry recordoutentry : recordoutentryList) {
            data.add(recordoutentry.getFnumber());
            data.add(recordoutentry.getFbizdate());
            data.add(recordoutentry.getFdescription());
            data.add(recordoutentry.getCheckName());
            data.add(recordoutentry.getCreateName());
            data.add(stateToString.billsState(recordoutentry.getCfbillstate()));
            data.add(recordoutentry.getUsername_v());
            data.add(recordoutentry.getCfstudentno());
            data.add(recordoutentry.getCfidcardno());
            data.add(recordoutentry.getCfcartype());
            data.add(recordoutentry.getCfcfwz());
            data.add(recordoutentry.getCfremark());
        }

        try {
            //导出Excel
            CommonExport.importExcel(response, "档案入库" + TimeFormat.getNowTime2() + ".xls", "档案入库", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/queryRecordout/look.action?state=first";
    }

}
